<?php
namespace Beerus\Modules\DecoCompany\Actions;

use Doraemon\model\DecoCompanyGroup as mDecoCompanyGroup;
use Doraemon\model\Member as mMember;
use Doraemon\model\DecoCompany as mDecoCompany;
use Doraemon\service\DecoCompany\DecoCompanyGroup as sDecoCompanyGroup;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class AddSubsidiary extends Action
{
    public $name = '添加分公司';

    protected $selector = '.add-subsidiary';

    public function handle(Request $request)
    {
        $urlParams = explode("/", $request->server('HTTP_REFERER'));
        $deco_id = $urlParams[count($urlParams)-2];
        if (empty($deco_id)) {
            return $this->response()->error('参数错误');
        }
        $deco_info = mDecoCompany::get('*', ['id'=>$deco_id]);
        switch ($deco_info['group_type']) {
            case mDecoCompany::GROUP_TYPE_SUBSIDIARY:
                $g_uid = mDecoCompanyGroup::getByCondition([
                    'd_uid' => $deco_info['uid'],
                    'g_status' => mDecoCompanyGroup::STATUS_NORMAL
                ], 'g_uid');
                break;
            case mDecoCompany::GROUP_TYPE_BLOC:
            default:
                $g_uid = $deco_info['uid'];
                break;
        }

        $uid = $request->post('uid');
        $nick = trim($request->post('nick'));

        $info = mDecoCompany::get('*', ['uid'=>$uid]);
        if (empty($info)) {
            return $this->response()->error('公司信息填写有误，请确认后再提交');
        }
        $companyNick = mMember::getNickByUid($uid);
        if ($nick != $companyNick) {
            return $this->response()->error('公司信息填写有误，请确认后再提交');
        }
        if ($info['group_type'] != mDecoCompany::GROUP_TYPE_NO) {
            return $this->response()->error("添加失败，{$nick} 已与其它公司绑定");
        }

        try {
            sDecoCompanyGroup::createGroupInfo($g_uid, $info['uid']);
        } catch (\Exception $e) {
            return $this->response()->error("添加失败，".$e->getMessage());
        }

        return $this->response()->success('添加成功')->refresh();
    }

    public function form()
    {
        $this->text("uid", "公司UID")->required();
        $this->text("nick", "公司昵称")->required();
    }

    public function html()
    {
        return <<<HTML
        <div style="height: 32px;"><a class="btn btn-sm btn-primary add-subsidiary" style="position: absolute;right: 10px;">添加分公司</a></div>
HTML;
    }
}